<?php

namespace app\store\task;

use think\facade\Db;
use yunwuxin\cron\Task;

class OrderTask extends Task
{
    public function configure()
    {
        $this->everyMinute();
    }

    /**
     * 执行任务
     * @return mixed
     */
    protected function execute()
    {
        $orders = Db::name('order')
                    ->field('id,user_id,give_integral,create_time')
                    ->where('status',3)
                    ->select();

        if (!$orders->isEmpty()){
            foreach ($orders as $v){
               if ($v['create_time']+7*24*3600 >= time()){
                   Db::startTrans();
                   try {
                       Db::name('order')->field('give_integral')->where('id',$v['id'])->update(['status' => 4]);
                       if ($v['give_integral']>0){
                           Db::name('user')->where('user_id',$v['user_id'])->inc('integral',$v['give_integral'])->update();
                           Db::name('user_integral_detail')->insert([
                               'user_id' => $v['user_id'],
                               'change_desc' => '订单交易',
                               'change_type' => 1,
                               'change_integral' => $v['give_integral'],
                               'change_time' => time()
                           ]);
                       }
                       Db::commit();
                   }catch(\Exception $e){
                        Db::rollback();
                   }


               }
            }
        }
    }

}